<?php
/**
 * Magento Enterprise Edition
 *
 * NOTICE OF LICENSE
 *
 * This source file is subject to the Magento Enterprise Edition End User License Agreement
 * that is bundled with this package in the file LICENSE_EE.txt.
 * It is also available through the world-wide-web at this URL:
 * http://www.magento.com/license/enterprise-edition
 * If you did not receive a copy of the license and are unable to
 * obtain it through the world-wide-web, please send an email
 * to license@magento.com so we can send you a copy immediately.
 *
 * DISCLAIMER
 *
 * Do not edit or add to this file if you wish to upgrade Magento to newer
 * versions in the future. If you wish to customize Magento for your
 * needs please refer to http://www.magento.com for more information.
 *
 * @category    design
 * @package     default_default
 * @copyright Copyright (c) 2006-2015 X.commerce, Inc. (http://www.magento.com)
 * @license http://www.magento.com/license/enterprise-edition
 */
?>
<?php
/**
 * Template for Mage_Adminhtml_Block_Catalog_Product_Edit
 */
?>



<div class="content-header">
    <h3 class="icon-head head-products"><?php echo $this->getHeader() ?></h3>
    <p class="content-buttons form-buttons"><?php echo $this->getBackButtonHtml() ?>
    <?php echo $this->getCancelButtonHtml() ?>
    <?php if($this->getProductId()): ?>
        <?php echo $this->getDeleteButtonHtml() ?>
        <?php if($this->getProductSetId() && $this->getIsConfigured()): ?>
            <?php echo $this->getDuplicateButtonHtml() ?>
        <?php endif; ?>
    <?php endif; ?>
    <?php if($this->getProductSetId() && $this->getIsConfigured()): ?>
        <?php echo $this->getSaveButtonHtml() ?>
        <?php echo $this->getSaveAndEditButtonHtml() ?>
    <?php endif; ?>
    </p>
</div>
<form action="<?php echo $this->getSaveUrl() ?>" method="post" id="product_edit_form" enctype="multipart/form-data">
    <?php echo $this->getBlockHtml('formkey')?>
    <div style="display:none"></div>
</form>
<script type="text/javascript">
//<![CDATA[
    var productTemplateSyntax = /(^|.|\r|\n)({{(\w+)}})/;
    var productForm = new varienForm('product_edit_form', '<?php echo $this->getValidationUrl() ?>');
    productForm._processValidationResult = function(transport) {
        var response = transport.responseText.evalJSON();
        if (response.error){
            if (response.attribute && $(response.attribute)) {
                $(response.attribute).setHasError(true, productForm);
                Validation.ajaxError($(response.attribute), response.message);
                if (!Prototype.Browser.IE){
                    $(response.attribute).focus();
                }
            }
            else if ($('messages')) {
                $('messages').innerHTML = '<ul class="messages"><li class="error-msg"><ul><li>' + response.message + '</li></ul></li></ul>';
            }
        }
        else{
            productForm._submit();
        }
    };
    function saveAndContinueEdit(urlTemplate) {
        var template = new Template(urlTemplate, productTemplateSyntax);
        var url = template.evaluate({tab_id:product_info_tabsJsTabs.activeTab.id});
        productForm.submit(url);
    }
    function setSettings(urlTemplate, setElement, typeElement) {
        var template = new Template(urlTemplate, productTemplateSyntax);
        setLocation(template.evaluate({attribute_set:$F(setElement),type:$F(typeElement)}));
    }

     function setSuperSettings(urlTemplate, attributesClass, validateField) {
        var attributesFields = $$('.' + attributesClass);
        var attributes = Form.serializeElements(attributesFields, true).attribute;
        if(typeof attributes == 'string') {
            attributes = [attributes];
        }

        if(!attributes) {
            $(validateField).value = 'no-attributes';
        } else {
            $(validateField).value = 'has-attributes';
        }

        if (productForm.validator.validate()) {
            var template = new Template(urlTemplate, productTemplateSyntax);
            var url = template.evaluate({
                attributes: encode_base64(attributes.join(',')).replace(new RegExp('/','g'),'%2F').replace(new RegExp('=','g'),'%3D')
            });
            setLocation(url);
        }
    }

    function checkMaxLength(Object, MaxLen)
    {
        if (Object.value.length > MaxLen-1) {
            Object.value = Object.value.substr(0, MaxLen);
        }
        return 1;
    }

Event.observe(window, 'load', function() {
    var objName = '<?php echo $this->getSelectedTabId() ?>';
    if (objName) {
        obj = $(objName);
        //IE fix (bubbling event model)
        product_info_tabsJsTabs.setSkipDisplayFirstTab();
        product_info_tabsJsTabs.showTabContent(obj);
    }
    Product.AttributesBridge.setTabsObject(product_info_tabsJsTabs);
});

Validation.addAllThese([
    ['validate-super-product-attributes', '<?php echo Mage::helper('core')->jsQuoteEscape(Mage::helper('catalog')->__('Please select one or more attributes.')) ?>', function(v) {
                return (v != "no-attributes");
            }]]);
//]]>
</script>


<!--lie 2016-03-24-->
<script type="text/javascript">

//<![CDATA[


    /*lie 2016-03-02 */

    /* 
     * 属性联动
     * 如果审核通过了，status才能是enabled。否则都为disabled.
     */
    changeOptionValueByOtherOptionValue('approval','2','status','1','2');

    /*特价自动加运费*/
    // specialPrice('common_supplier_special_price');
	// specialPrice('cost');
    
    /*运费查询*/
    // shippingQuery('common_weight');
    // shippingQuery('common_package_length');
    // shippingQuery('common_package_width');
    // shippingQuery('common_package_height');
    // shippingQuery('common_shipping_type');
    // shippingQuery('common_supply_price');
    // shippingQuery('common_dimensional_weight');
    // shippingQuery('vendor_id');

	
	
	
	
	/* 特价价格填写完之后，自动加上运费 */
	function specialPrice(idName)
	{
		addRemark('special_price', 'Special Price = (Supplier Special Price + Cost Price) / 0.95');
		var idObject = document.getElementById(idName);
		if (idObject)
		{
			idObject.onblur=function()
			{

				/*必需这两个选项都有值，才触发给specialPrice填写价格。*/
				var supplierSpecialPrice = checkHasValue('common_supplier_special_price');
				var cost  = checkHasValue('cost');
				
        		if(supplierSpecialPrice && cost){
					var specialPrice = document.getElementById('special_price');
					specialPrice.value = ((Number(supplierSpecialPrice) + Number(cost)) / 0.95).toFixed(2); 
				}
				else{
					var specialPrice = document.getElementById('special_price');
					specialPrice.value = '';
				}
			}
		}
	}
	
	function addRemark(idName, Text)
	{
		var idObject = document.getElementById(idName);
		var createDiv=document.createElement("div");
		createDiv.setAttribute("id", "massage_" + idName);
		createDiv.innerHTML=Text;
		if(document.getElementById("massage_" + idName) == null)
		{
			idObject.parentNode.appendChild(createDiv);
		}
	}
	

    /* 
     * 属性联动(select类型)，根据fromId属性的fromValue值自动更改toId属性的toValue值, 
     * fromId其他的非fromValue值则都改为toId的toOtherValue的值.
     */
    function changeOptionValueByOtherOptionValue(fromId,fromValue,toId,toValue,toOtherValue)
    {
        var fromObject = document.getElementById(fromId);
        var toObject   = document.getElementById(toId);
        if(fromObject && toObject)
        {
            fromObject.onblur=function()
            {
                if(fromObject.value == fromValue)
                {
                    for(var i=0;i<toObject.options.length;i++)
                    {
                        if(toObject.options[i].value == toValue)
                        {
                            toObject.options[i].selected=true;
                        }
                    }
                }
                else
                {
                    for(var i=0;i<toObject.options.length;i++)
                    {
                        if(toObject.options[i].value == toOtherValue)
                        {
                            toObject.options[i].selected=true;
                        }
                    }
                }
            }
        }
    }

    /*查询运费方法*/

	function shippingQuery(idName)
	{
		var idObject = document.getElementById(idName);
		if (idObject)
		{
			idObject.onblur=function()
			{

				/*必需这六个选项都有值，才触发运费查询的ajax请求。*/
				var vendorWeight 		= checkHasValue('common_weight');
				var vendorPackageLength = checkHasValue('common_package_length');
				var vendorPackageWidth  = checkHasValue('common_package_width');
				var vendorPackageHeight = checkHasValue('common_package_height');
				var vendorShippingType  = checkHasValue('common_shipping_type');
				vendorSupplyPrice   	= checkHasValue('common_supply_price');

				if(vendorWeight && vendorPackageLength && vendorPackageWidth && vendorPackageHeight 
					&& vendorShippingType && vendorSupplyPrice)
				{
					var packageWeight = ((vendorPackageLength * vendorPackageWidth * vendorPackageHeight) / 12000).toFixed(2);
					if(vendorShippingType == '14') /* 判断是否是电商专递，如果不是则直接取真实重量 */
					{
						if(packageWeight > vendorWeight) /*体积重>重量，为轻抛物，按体积重算*/
						{
							var finalWeight   = packageWeight;
						}
						else
						{
							var finalWeight   = vendorWeight;
						}
					}
					else
					{
						var finalWeight   = vendorWeight;
					}
					console.log('finalWeight = ' + finalWeight);
					
					var Url = "<?php echo Mage::getUrl("shippingquery/vendor/query/") ?>";
					var vendorId = "<?php echo Mage::getSingleton('vendors/session')->getVendor()->getId();?>";
					new Ajax.Request(Url, 
					{
						method: 'post',
						parameters: {weight: finalWeight, shippingcode: vendorShippingType, vendorid: vendorId},
						onSuccess: function(transport) {
							var returnPrice = transport.responseText
							document.getElementById('cost').value = returnPrice;
							document.getElementById('price').value = ((Number(returnPrice) + Number(vendorSupplyPrice)) / 0.95).toFixed(2);
						}
					});
				}
	    	}
		
		}
	}

    function checkHasValue(idName)
    {   
        var idObject = document.getElementById(idName);
        
        if(idObject.value != '')
        {
            
            if(idName == 'common_weight')
            {
                /*如果是common_weight,要把值赋给weight选项*/
                if(document.getElementById('weight'))
                {
                    document.getElementById('weight').value = idObject.value;
                }

                /*同时检测是否有超过2kg，超过就不能选小包类型*/
                if(Number(idObject.value) > 2)
                    {
                        idObject1 = document.getElementById('common_shipping_type');
                        
                        for(var i=0;i<idObject1.options.length;i++)
                        {
                            if(idObject1.options[i].value == '14')
                            {
                                idObject1.options[i].selected = true;
                            }
                            else
                            {
                                idObject1.options[i].disabled = true;
                            }
                            
                        }
                        
                        var createDiv=document.createElement("div");
                        createDiv.setAttribute("id", "Massage_onlyselect_common_shipping_type");
                        createDiv.setAttribute("class", "validation-advice");
                        createDiv.innerHTML="Weight is greater than 2kg. Only select Ecommerce Express.";
                        if(document.getElementById("Massage_onlyselect_common_shipping_type") == null)
                        {
                            idObject1.parentNode.appendChild(createDiv);
                        }
                        
                    }
                    else
                    {
                        idObject1 = document.getElementById('common_shipping_type');
                        
                        for(var i=0;i<idObject1.options.length;i++)
                        {
                            idObject1.options[i].disabled = false;
                        }

                        massageDiv = document.getElementById("Massage_onlyselect_common_shipping_type");
                        if( massageDiv != null)
                        {
                            massageDiv.parentNode.removeChild(massageDiv);
                        }
                    }
            }

            return idObject.value;
        }
        else
        {
            return false;
        }
    }

//]]>
</script>



<script type="text/javascript">
    //<![CDATA[
/*you 是否带电和带电证书有效期关联功能 2016-4-11*/
    var weightject = document.getElementById('common_is_charged');
    var codeject   = document.getElementById('common_msds');

    var labelject  = document.getElementsByTagName("label");
    var labelspan = "<span class='required'> *</span>";
    if(weightject)
    {
        weightject.onblur=function()
        {
            var weightjectValue = weightject.value;

            if(weightjectValue == 1)
            {
                if(codeject)
                {   
                    var beforeClass     = codeject.className;
                    if(beforeClass.indexOf('required-entry')<0)
                    {
                        var beforemyClass  = beforeClass+' required-entry';
                        codeject.className = beforemyClass;
                    }
                    var labelhtml      = getLabelForValue(labelject,codeject);
                    var labelspanval   = labelhtml.lastChild;
                    if(labelspanval.nodeName != 'SPAN'){
                        var labeltext      = labelhtml.innerHTML;
                        labelhtml.innerHTML= labeltext+labelspan;
                    }
                }
            }else if(weightjectValue ==0){
                if(codeject)
                {
                    codeject.className = codeject.className.replace(' required-entry', '');
                    var labelhtml      = getLabelForValue(labelject,codeject);
                    var labelspanval   = labelhtml.lastChild;
                    if(labelspanval.nodeName == 'SPAN'){
                        labelhtml.removeChild(labelspanval);
                    }
                }
            }
        }
    }
    function getLabelForValue(labelject,codeject)
    {
        for(i=0;i<labelject.length;i++)
        {
            var forvalue=labelject[i].getAttributeNode("for").value;
            if(forvalue==codeject.id)
            {                         
                return labelject[i];
            }
        }
    }
/*you 是否带电和带电证书有效期关联功能 2016-4-11*/


/*
* you 后台产品编辑页取消三审选择状态 2016-07-21
*/
var approvalStost = document.getElementById('approval').options['6'].disabled='true';
/* you 后台产品编辑页取消三审选择状态 2016-07-21*/
    //]]>
</script>
